package me.cunity.service;
import htemplate.Template;
import php.io.File;
import php.Web;

/**
 * ...
 * @author Axel Huizinga axel@cunity.me
 */

class Templater
{

	public static function process(s:Service, path:String, obj:Dynamic):String
	{
		/*
		 * 1. load and parse locale
		 * 2. load and process template
		*/
		var xml:Xml = null;
		try {
			xml = Xml.parse(File.getContent(s.templateDir + 'locale/' + path));
			if (xml.firstChild().nodeName == 'locale')
			{
				for (el in xml.firstChild().elements())
					Reflect.setField(obj, el.nodeName, el.toString());
				var tmp:Template = new Template(File.getContent(s.templateDir + path));
				return tmp.execute(obj);
			}
			return '';
		}
		catch (ex:Dynamic)
		{
			return(ex);
		}				
	}
	
	public static function getSystemTemplate(s:Service, keys:Array<String>, ?data:Dynamic):String
	{
		var processed:String = '';
		//var strings:String = File.getContent(s.templateDir + 'locale/' + s.locale + '/strings.xml');
		//s.errLog('<textarea cols="60" rows="10">'+strings+'</textarea>');
		var xml:Xml =  (data == null ? Xml.parse(File.getContent(s.templateDir + 'locale/' + s.locale + '/strings.xml')) : 
		Xml.parse(new Template(File.getContent(s.templateDir + 'locale' + s.locale + '/strings.xml')).execute(data)));
		s.errLog('xml::nodeName:' + xml.firstElement().nodeName);
		//s.errLog('xml::firstChild' + xml.elements());
		if (xml.firstElement().nodeName == 'locale')
		{		
			for (key in keys)
			{
				var els:Iterator<Xml> = xml.firstElement().elementsNamed(key);
				if (els.hasNext())
				{
					//s.errLog(els.next().toString());
					var el:Xml = els.next();
					if (Lambda.has(keys, el.nodeName))
					{
						s.errLog(el.nodeType + ':' + el.firstChild().nodeType);
						
						processed += el.firstChild().toString();
					}
				}
			}
		}
		return processed;
	}
	
}